const BaseController = require("../core/baseController");

// 商品信息
class CommodityController extends BaseController {
  // 查询
  // all 才是真的所有的总数，ret的总数是被limit过的不准确
  async fetchList() {
    const query = this.ctx.query;
    try {
      const ret = await this.service.commodity.findList(query);
      const all = await this.service.commodity.fetchAll();
      this.successForList(ret, query.pageSize, query.currentPage, all);
    } catch (e) {
      this.failure("查询失败");
    }
  }

  // 新增
  async create() {
    const {ctx, service} = this;
    let params = {
      name: ctx.request.body.name,
      picture: ctx.request.body.picture,
      price: ctx.request.body.price,
      vipPrice: ctx.request.body.vipPrice,
      discount: ctx.request.body.discount,
      sort: ctx.request.body.sort,
      menuId: ctx.request.body.menuId
    };
    try {
      await service.commodity.add(params);
      const ret = await this.service.commodity.findList({
        currentPage: 1,
        pageSize: 10
      });
      this.successForList(ret);
    } catch (e) {
      this.failure("新增失败", e);
    }
  }

  //  更新接口
  async update() {
    const {ctx, service} = this;
    let params = {
      _id: ctx.request.body._id,
      name: ctx.request.body.name,
      picture: ctx.request.body.picture,
      price: ctx.request.body.price,
      vipPrice: ctx.request.body.vipPrice,
      discount: ctx.request.body.discount,
      sort: ctx.request.body.sort
    };
    try {
      await service.commodity.update(params);
      const ret = await this.service.commodity.findList({
        currentPage: 1,
        pageSize: 10
      });
      this.successForList(ret, 10, 1);
    } catch (e) {
      this.failure("更新失败");
    }
  }

  // 删除
  async delete() {
    const {ctx, service} = this;
    const _ids = ctx.request.body._ids.split(",");
    try {
      await service.commodity.delete(_ids);
      const ret = await this.service.commodity.findList({
        currentPage: 1,
        pageSize: 10
      });
      this.successForList(ret, 10, 1);
    } catch (e) {
      this.failure("删除失败");
    }
  }

  async deleteAll() {
    try {
      await this.service.commodity.deleteAll();
    } catch (e) {
      this.failure("删除失败", e);
    }
  }

  async findById() {
    const {ctx, service} = this;
    const _id = ctx.params.type;
    try {
      const ret = await service.commodity.findById(_id);
    } catch (e) {
    }
  }

  async search() {
    const {ctx, service} = this;
    const query = ctx.request.body.name;
    try {
      const result = await service.commodity.search(query);
      this.success(result);
    } catch (e) {
      this.failure("查询失败", e);
    }
  }

  async findAll() {
    const {service} = this;
    try {
      const result = await service.commodity.findAll();
      this.success(result)
    } catch (e) {
      this.failure("查询失败", e);
    }
  }
}

module.exports = CommodityController;
